package goci

import (
	"path/filepath"
	"runtime"

	"gitee.com/githubdog/goci/gclang"
	"gitee.com/githubdog/goci/libraries/mylog"
	"gitee.com/githubdog/goci/system/db/model"
	"gitee.com/githubdog/goci/tools/myerr"
)

var (
	gociConf GcConf
	gociPath string
)

type GcLog struct {
	LogPath string
}

type GcLang struct {
	DefaultLang string
	DirName     string
	LangMap     map[string]string
	DirArr      []string
}

// GcConf goci config
type GcConf struct {
	ProjectDir  string
	ProjectName string
	IsDebug     bool
	GcDb        model.ModelConf
	GcLog
	GcLang
}

type GoCI struct {
	*model.Model
	ResObj    *myerr.ResError
	sessionid string
	modelLogs []string
}

func GetGoCIPath(depth uint8) string {
	if gociPath == "" {
		_, file, _, ok := runtime.Caller(0)
		if ok {
			for i := 0; i <= int(depth); i++ {
				file = filepath.Dir(file)
			}
			gociPath = file
		}
	}
	return gociPath
}

func SetGoCIConf(gc GcConf) {
	gociConf = gc
	// db
	model.SetConfig(gc.GcDb)
	// lang
	gclang.InitLang(gc.DefaultLang, gc.ProjectDir+gc.GcLang.DirName, gc.LangMap)
	if gcPath := GetGoCIPath(0); gcPath != "" {
		gclang.LoadLangFile([]string{gcPath + "/lang"})
	}
	gclang.LoadLangFile(gc.DirArr)
	// log
	mylog.InitLog(gc.ProjectDir + gc.LogPath)
}

func NewGoCI() *GoCI {
	ci := new(GoCI)
	ci.ResObj = myerr.New()
	ci.Model = model.New()

	return ci
}

func NewResponse() *myerr.ResError {
	return myerr.New().SetErrShow(gociConf.IsDebug)
}

func (gc *GoCI) GetSessionID() string {
	return gc.sessionid
}

func (gc *GoCI) RequestEnd(dblog bool) {
	// gc.Model.WriteDBLog(gc.sessionid, dblog)
	Remove(gc.sessionid)
}

func (gc *GoCI) AppendModelLogs(m *model.Model) {
	gc.modelLogs = append(gc.modelLogs, m.GetLogs()...)
}
